package com.example.smartg;

import android.os.Bundle;

import com.google.android.material.snackbar.Snackbar;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;

import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import okhttp3.Call;
import okhttp3.Response;
import tp.xmaihh.serialport.SerialHelper;
import tp.xmaihh.serialport.bean.ComBean;
import tp.xmaihh.serialport.stick.AbsStickPackageHelper;
import tp.xmaihh.serialport.utils.ByteUtil;

import com.example.smartg.databinding.ActivityMainBinding;

import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;

public class MainActivity extends AppCompatActivity {

    private AppBarConfiguration appBarConfiguration;
    private ActivityMainBinding binding;
    // 串口配置
    public static SerialHelper serialHelper;
    public static String SPORT_NAME = "/dev/ttyS4"; //串口路径
    //    public static String SPORT_NAME = "/dev/ttyUSB2"; //串口路径
    public static int BAUD_RATE = 19200; //波特率


    /**
     * 串口配置/接收返回的数据
     * （在哪调用这函数都行，只需放在打开串口之前就行了）
     */
    public static void initSerialConfig() {
        //初始化SerialHelper对象，设定串口名称和波特率
        serialHelper = new SerialHelper(SPORT_NAME, BAUD_RATE) {
            @Override
            protected void onDataReceived(ComBean paramComBean) {
                Message message = mHandler.obtainMessage();
                message.obj = paramComBean;
                mHandler.sendMessage(message);
            }
        };

        /*
         * 默认的BaseStickPackageHelper将接收的数据扩展成64位，一般用不到这么多位
         * 我这里重新设定一个自适应数据位数的
         */
        serialHelper.setStickPackageHelper(new AbsStickPackageHelper() {
            @Override
            public byte[] execute(InputStream is) {
                try {
                    int available = is.available();
                    if (available > 0) {
                        byte[] buffer = new byte[available];
                        int size = is.read(buffer);
                        if (size > 0) {
                            return buffer;
                        }
                    } else {
                        SystemClock.sleep(50);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }
        });
    }


    //接收到的数据
    public static Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            ComBean comBean = (ComBean) msg.obj;
            //获取数据
            String str = ByteUtil.ByteArrToHex(comBean.bRec);
            System.out.println(str);
            String url = "http://10.2.47.115/pda_manage_api/get_bind_status";
            //实例化
            HttpUtil httpUtil = new HttpUtil();
            JSONObject json = new JSONObject();
            try {
                json.put("rfid_text", "xxxxxx");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            httpUtil.sendOkHttpRequest(url, json.toString(), new okhttp3.Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.e("exception", e.toString());
                    //ToatUtil.showMsg(MainActivity.this, "HTTP FAIL!");
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String responsedata = response.body().string();
                    JSONObject jsonObject = null;
                    try {
                        jsonObject = new JSONObject(responsedata);
                        String msg = jsonObject.optString("msg");
                        Log.e("result:", msg);   //解析从服务器返回json数据
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


                }
            });
            return false;
        }
    });

    //打开串口（先配置，再打开串口）
    public static boolean openSerialHelper() {
        //已经打开串口了就不用再打开
        if (serialHelper.isOpen()) return false;
        //打开串口
        try {
            serialHelper.open();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return true;
    }

    //关闭串口（注销时候或手动关闭）
    public static boolean closeSerialHelper() {
        if (!serialHelper.isOpen()) return false;
        serialHelper.close();
        return true;
    }


    private String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }


    private static void open(String cmd_hex) {
        serialHelper.sendHex(cmd_hex); //十六进制数
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        setSupportActionBar(binding.toolbar);

        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
        appBarConfiguration = new AppBarConfiguration.Builder(navController.getGraph()).build();
        NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);

        binding.fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });


        // 测试串口通信
        initSerialConfig();
        openSerialHelper();

        Button btn = (Button) findViewById(R.id.button_first);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                for(int i=1;i<=10;i++){
                    try {
                        Thread.sleep(400);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onSupportNavigateUp() {
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
        return NavigationUI.navigateUp(navController, appBarConfiguration)
                || super.onSupportNavigateUp();
    }

    @Override
    public void onDestroy() {
        closeSerialHelper();
        super.onDestroy();
    }

}